import api from '@/api';
import storage from 'js-storage';
const userInfo = storage.localStorage.get('userInfo');
const menu = storage.localStorage.get('menu') || [];
const name = userInfo ? userInfo.name : '';

export default {
  namespaced: true,
  state: {
    name,
    avatar: '',
    userInfo,
    menu,
  },
  getters: {},
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
      storage.localStorage.set('userInfo', userInfo);

      state.name = userInfo.name;
      state.avatar = userInfo.avatar;
    },
    removeUserInfo(state) {
      state.userInfo = null;
      storage.localStorage.set('userInfo', null);
    },
    setMenu(state, val) {
      state.menu = val;
      storage.localStorage.set('menu', val);
    },
  },
  actions: {
    // 登录 - 纯登录，不做任何操作，通过 set-cookie 处理 token
    login({ commit }, userInfo) {
      return api.user.login(userInfo).then(({ data }) => {
        commit('setUserInfo', data);
        commit(
          'setMenu',
          JSON.parse(data.role.functions).filter(item => item.authority)
        );
      });
    },

    // 登出
    logout({ commit }) {
      commit('removeUserInfo');
      // return api.user.logout().then(() => {
      // });
    },

    getUserInfo({ commit }) {
      return api.user.getUserInfo().then(({ data }) => {
        commit('setUserInfo', data);
        return data;
      });
    },
  },
};
